import json
import os
from datetime import datetime
from typing import Dict, List, Any, Optional
import logging
import matplotlib.pyplot as plt
import pandas as pd
from jinja2 import Template

class ReportGenerator:
    """
    报告生成器，用于生成测试执行结果和性能优化报告
    - 支持JSON、HTML、图表等多种格式输出
    - 包含执行摘要、性能指标、优化效果对比
    - 可视化展示性能提升数据
    """
    
    def __init__(self):
        """
        初始化报告生成器
        """
        self.logger = logging.getLogger('ReportGenerator')
        self.report_dir = './reports'
        os.makedirs(self.report_dir, exist_ok=True)
        self.logger.info("报告生成器初始化完成")
    
    def generate_report(self,
                        test_results: Dict[str, Any],
                        performance_data: Dict[str, Any],
                        output_formats: List[str] = None,
                        output_dir: str = None) -> List[str]:
        """
        生成报告
        
        Args:
            test_results: 测试结果数据
            performance_data: 性能数据
            output_formats: 输出格式列表，支持 ['json', 'html', 'charts']
            output_dir: 输出目录
            
        Returns:
            生成的报告文件路径列表
        """
        if output_formats is None:
            output_formats = ['json', 'html']
        
        if output_dir:
            self.report_dir = output_dir
            os.makedirs(self.report_dir, exist_ok=True)
        
        # 生成报告ID和文件名
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        report_id = f"report_{timestamp}"
        
        generated_files = []
        
        # 合并数据
        report_data = self._merge_data(test_results, performance_data)
        
        # 生成JSON报告
        if 'json' in output_formats:
            json_path = self._generate_json_report(report_data, report_id)
            generated_files.append(json_path)
        
        # 生成HTML报告
        if 'html' in output_formats:
            html_path = self._generate_html_report(report_data, report_id)
            generated_files.append(html_path)
        
        # 生成图表
        if 'charts' in output_formats:
            chart_paths = self._generate_charts(report_data, report_id)
            generated_files.extend(chart_paths)
        
        self.logger.info(f"已生成报告文件: {', '.join(generated_files)}")
        return generated_files
    
    def _merge_data(self, test_results: Dict[str, Any], performance_data: Dict[str, Any]) -> Dict[str, Any]:
        """
        合并测试结果和性能数据
        
        Args:
            test_results: 测试结果
            performance_data: 性能数据
            
        Returns:
            合并后的数据
        """
        # 计算优化目标达成情况
        optimization_goals = self._calculate_optimization_goals(performance_data)
        
        merged_data = {
            'metadata': {
                'generated_at': datetime.now().isoformat(),
                'report_version': '1.0'
            },
            'test_summary': self._extract_test_summary(test_results),
            'performance_metrics': performance_data,
            'optimization_analysis': optimization_goals,
            'detailed_results': test_results
        }
        
        return merged_data
    
    def _extract_test_summary(self, test_results: Dict[str, Any]) -> Dict[str, Any]:
        """
        提取测试摘要信息
        
        Args:
            test_results: 测试结果
            
        Returns:
            测试摘要
        """
        total_tests = test_results.get('total_tests', 0)
        passed_tests = test_results.get('passed_tests', 0)
        failed_tests = test_results.get('failed_tests', 0)
        skipped_tests = test_results.get('skipped_tests', 0)
        
        pass_rate = (passed_tests / total_tests * 100) if total_tests > 0 else 0
        
        return {
            'total_tests': total_tests,
            'passed_tests': passed_tests,
            'failed_tests': failed_tests,
            'skipped_tests': skipped_tests,
            'pass_rate': pass_rate,
            'execution_time': test_results.get('total_execution_time', 0),
            'parallel_degree': test_results.get('parallel_degree', 1)
        }
    
    def _calculate_optimization_goals(self, performance_data: Dict[str, Any]) -> Dict[str, Any]:
        """
        计算优化目标达成情况
        
        Args:
            performance_data: 性能数据
            
        Returns:
            优化目标达成分析
        """
        # 目标性能提升300%
        target_improvement = 300.0
        
        # 获取实际性能提升
        actual_improvement = 0.0
        if 'performance_improvement' in performance_data:
            actual_improvement = performance_data['performance_improvement'].get('overall_performance_improvement', 0)
        
        # 达成率
        achievement_rate = min(actual_improvement / target_improvement * 100, 100)
        
        # 效率收益分析
        efficiency_analysis = self._analyze_efficiency_gains(performance_data)
        
        return {
            'target_improvement': target_improvement,
            'actual_improvement': actual_improvement,
            'achievement_rate': achievement_rate,
            'is_goal_achieved': actual_improvement >= target_improvement,
            'efficiency_gains': efficiency_analysis,
            'recommendations': self._generate_recommendations(performance_data)
        }
    
    def _analyze_efficiency_gains(self, performance_data: Dict[str, Any]) -> Dict[str, Any]:
        """
        分析效率收益
        
        Args:
            performance_data: 性能数据
            
        Returns:
            效率收益分析
        """
        gains = {
            'time_saved_seconds': 0,
            'resource_cost_reduction': 0,
            'cost_per_test': 0,
            'roi_analysis': {}
        }
        
        # 计算节省的时间
        if 'performance_improvement' in performance_data:
            improvement = performance_data['performance_improvement']
            total_duration = performance_data.get('total_duration', 0)
            
            # 计算原来的预计时间
            if improvement.get('time_reduction_percentage', 0) > 0:
                time_reduction_pct = improvement['time_reduction_percentage'] / 100
                original_time = total_duration / (1 - time_reduction_pct)
                gains['time_saved_seconds'] = original_time - total_duration
        
        # 计算资源成本减少
        if 'resource_utilization' in performance_data:
            # 这里简化计算，实际可能需要更复杂的资源成本模型
            cpu_util = performance_data['resource_utilization']['cpu'].get('average', 0)
            memory_util = performance_data['resource_utilization']['memory'].get('average_mb', 0)
            
            # 假设计算资源成本
            gains['resource_cost_reduction'] = (cpu_util + memory_util / 1024) * 0.01
        
        return gains
    
    def _generate_recommendations(self, performance_data: Dict[str, Any]) -> List[str]:
        """
        生成优化建议
        
        Args:
            performance_data: 性能数据
            
        Returns:
            建议列表
        """
        recommendations = []
        
        # 基于CPU使用率的建议
        if 'resource_utilization' in performance_data:
            cpu_util = performance_data['resource_utilization']['cpu'].get('average', 0)
            cpu_count = performance_data['resource_utilization']['cpu'].get('utilization_percentage', 0)
            
            if cpu_util < 50:
                recommendations.append("CPU利用率较低，建议增加并行度以充分利用系统资源")
            elif cpu_util > 90:
                recommendations.append("CPU利用率过高，可能导致资源竞争，建议降低并行度或优化测试代码")
            
            if cpu_count < 70:
                recommendations.append(f"当前只使用了约{cpu_count:.1f}%的CPU核心，建议增加并行度")
        
        # 基于内存使用的建议
        memory_util = performance_data['resource_utilization']['memory'].get('average_percentage', 0)
        if memory_util > 85:
            recommendations.append("内存使用率较高，可能存在内存泄漏风险，建议检查测试资源释放")
        
        # 基于性能提升的建议
        if 'performance_improvement' in performance_data:
            improvement = performance_data['performance_improvement']
            overall = improvement.get('overall_performance_improvement', 0)
            
            if overall < 200:
                recommendations.append(f"当前性能提升为{overall:.1f}%，距离300%目标还有差距，建议进一步优化智能等待和资源复用")
            elif overall >= 300:
                recommendations.append("🎉 已达到300%性能提升目标！建议继续监控稳定性")
        
        # 默认建议
        if not recommendations:
            recommendations.append("继续监控系统性能，定期分析瓶颈并优化")
        
        return recommendations
    
    def _generate_json_report(self, report_data: Dict[str, Any], report_id: str) -> str:
        """
        生成JSON格式报告
        
        Args:
            report_data: 报告数据
            report_id: 报告ID
            
        Returns:
            JSON文件路径
        """
        json_path = os.path.join(self.report_dir, f"{report_id}.json")
        
        try:
            with open(json_path, 'w', encoding='utf-8') as f:
                json.dump(report_data, f, indent=2, ensure_ascii=False)
            
            self.logger.info(f"JSON报告已生成: {json_path}")
            return json_path
        except Exception as e:
            self.logger.error(f"生成JSON报告失败: {str(e)}")
            raise
    
    def _generate_html_report(self, report_data: Dict[str, Any], report_id: str) -> str:
        """
        生成HTML格式报告
        
        Args:
            report_data: 报告数据
            report_id: 报告ID
            
        Returns:
            HTML文件路径
        """
        html_path = os.path.join(self.report_dir, f"{report_id}.html")
        
        # HTML模板
        html_template = """
        <!DOCTYPE html>
        <html lang="zh-CN">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>鸿蒙测试优化报告 - {{ report_id }}</title>
            <style>
                body {
                    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
                    line-height: 1.6;
                    color: #333;
                    max-width: 1200px;
                    margin: 0 auto;
                    padding: 20px;
                    background-color: #f5f5f5;
                }
                .header {
                    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                    color: white;
                    padding: 30px;
                    border-radius: 10px;
                    margin-bottom: 30px;
                    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
                }
                .header h1 {
                    margin: 0;
                    font-size: 2.5em;
                }
                .header p {
                    margin: 10px 0 0 0;
                    opacity: 0.9;
                }
                .section {
                    background: white;
                    padding: 25px;
                    margin-bottom: 20px;
                    border-radius: 8px;
                    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
                }
                .section h2 {
                    color: #444;
                    margin-top: 0;
                    border-bottom: 2px solid #667eea;
                    padding-bottom: 10px;
                }
                .stats-grid {
                    display: grid;
                    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
                    gap: 20px;
                    margin: 20px 0;
                }
                .stat-card {
                    background: #f8f9fa;
                    padding: 20px;
                    border-radius: 8px;
                    text-align: center;
                    border: 1px solid #e9ecef;
                }
                .stat-card .value {
                    font-size: 2em;
                    font-weight: bold;
                    margin-bottom: 5px;
                }
                .stat-card .label {
                    color: #666;
                    font-size: 0.9em;
                }
                .success {
                    color: #28a745;
                }
                .warning {
                    color: #ffc107;
                }
                .danger {
                    color: #dc3545;
                }
                .info {
                    color: #17a2b8;
                }
                .progress-container {
                    width: 100%;
                    height: 30px;
                    background: #e9ecef;
                    border-radius: 15px;
                    overflow: hidden;
                    margin: 20px 0;
                }
                .progress-bar {
                    height: 100%;
                    background: linear-gradient(90deg, #4caf50, #8bc34a);
                    text-align: center;
                    line-height: 30px;
                    color: white;
                    font-weight: bold;
                    transition: width 0.3s ease;
                }
                .goal-achieved .progress-bar {
                    background: linear-gradient(90deg, #ff5722, #ff9800);
                }
                table {
                    width: 100%;
                    border-collapse: collapse;
                    margin: 20px 0;
                }
                th, td {
                    padding: 12px;
                    text-align: left;
                    border-bottom: 1px solid #ddd;
                }
                th {
                    background-color: #f8f9fa;
                    font-weight: bold;
                }
                .recommendations {
                    background: #e3f2fd;
                    padding: 20px;
                    border-radius: 8px;
                    border-left: 4px solid #2196f3;
                }
                .recommendations ul {
                    margin: 0;
                    padding-left: 20px;
                }
                .recommendations li {
                    margin-bottom: 8px;
                }
                .footer {
                    text-align: center;
                    margin-top: 40px;
                    color: #666;
                    font-size: 0.9em;
                }
            </style>
        </head>
        <body>
            <div class="header">
                <h1>鸿蒙测试优化报告</h1>
                <p>生成时间: {{ generated_at }}</p>
            </div>
            
            <div class="section">
                <h2>测试执行摘要</h2>
                <div class="stats-grid">
                    <div class="stat-card">
                        <div class="value">{{ test_summary.total_tests }}</div>
                        <div class="label">总测试数</div>
                    </div>
                    <div class="stat-card">
                        <div class="value success">{{ test_summary.passed_tests }}</div>
                        <div class="label">通过测试</div>
                    </div>
                    <div class="stat-card">
                        <div class="value warning">{{ test_summary.failed_tests }}</div>
                        <div class="label">失败测试</div>
                    </div>
                    <div class="stat-card">
                        <div class="value info">{{ "%.1f" % test_summary.pass_rate }}%</div>
                        <div class="label">通过率</div>
                    </div>
                    <div class="stat-card">
                        <div class="value">{{ "%.2f" % test_summary.execution_time }}s</div>
                        <div class="label">总执行时间</div>
                    </div>
                    <div class="stat-card">
                        <div class="value">{{ test_summary.parallel_degree }}x</div>
                        <div class="label">并行度</div>
                    </div>
                </div>
            </div>
            
            <div class="section">
                <h2>性能优化目标达成情况</h2>
                <h3>目标：性能提升 300%</h3>
                <div class="progress-container {{ 'goal-achieved' if optimization_analysis.is_goal_achieved else '' }}">
                    <div class="progress-bar" style="width: {{ min(optimization_analysis.achievement_rate, 100) }}%">
                        {{ "%.1f" % optimization_analysis.actual_improvement }}% ({{ "%.1f" % optimization_analysis.achievement_rate }}% 目标达成率)
                    </div>
                </div>
                
                {% if optimization_analysis.is_goal_achieved %}
                <div class="success">🎉 恭喜！已成功达到 300% 性能提升目标！</div>
                {% else %}
                <div class="warning">继续优化，距离目标还有 {{ "%.1f" % (300 - optimization_analysis.actual_improvement) }}% 的提升空间</div>
                {% endif %}
                
                <h3>效率收益</h3>
                <ul>
                    <li>节省时间：{{ "%.2f" % optimization_analysis.efficiency_gains.time_saved_seconds }} 秒</li>
                    <li>资源成本降低：{{ "%.2f" % optimization_analysis.efficiency_gains.resource_cost_reduction }}%</li>
                </ul>
            </div>
            
            <div class="section">
                <h2>资源利用率分析</h2>
                <table>
                    <tr>
                        <th>资源类型</th>
                        <th>平均使用率</th>
                        <th>最大使用率</th>
                        <th>使用效率</th>
                    </tr>
                    <tr>
                        <td>CPU</td>
                        <td>{{ "%.1f" % performance_metrics.resource_utilization.cpu.average }}%</td>
                        <td>{{ "%.1f" % performance_metrics.resource_utilization.cpu.max }}%</td>
                        <td>{{ "%.1f" % performance_metrics.resource_utilization.cpu.utilization_percentage }}%</td>
                    </tr>
                    <tr>
                        <td>内存</td>
                        <td>{{ "%.1f" % performance_metrics.resource_utilization.memory.average_mb }} MB</td>
                        <td>{{ "%.1f" % performance_metrics.resource_utilization.memory.max_mb }} MB</td>
                        <td>{{ "%.1f" % performance_metrics.resource_utilization.memory.average_percentage }}%</td>
                    </tr>
                </table>
            </div>
            
            <div class="section">
                <h2>优化建议</h2>
                <div class="recommendations">
                    <ul>
                        {% for recommendation in optimization_analysis.recommendations %}
                        <li>{{ recommendation }}</li>
                        {% endfor %}
                    </ul>
                </div>
            </div>
            
            <div class="footer">
                <p>鸿蒙测试优化器 v1.0 | 由 Harmony Test Optimizer 生成</p>
            </div>
        </body>
        </html>
        """
        
        try:
            # 渲染HTML
            template = Template(html_template)
            html_content = template.render(
                report_id=report_id,
                generated_at=report_data['metadata']['generated_at'],
                test_summary=report_data['test_summary'],
                performance_metrics=report_data['performance_metrics'],
                optimization_analysis=report_data['optimization_analysis']
            )
            
            # 保存HTML文件
            with open(html_path, 'w', encoding='utf-8') as f:
                f.write(html_content)
            
            self.logger.info(f"HTML报告已生成: {html_path}")
            return html_path
        except Exception as e:
            self.logger.error(f"生成HTML报告失败: {str(e)}")
            raise
    
    def _generate_charts(self, report_data: Dict[str, Any], report_id: str) -> List[str]:
        """
        生成性能图表
        
        Args:
            report_data: 报告数据
            report_id: 报告ID
            
        Returns:
            图表文件路径列表
        """
        chart_paths = []
        
        try:
            # 创建图表目录
            chart_dir = os.path.join(self.report_dir, 'charts')
            os.makedirs(chart_dir, exist_ok=True)
            
            # 生成性能提升对比图
            improvement_chart = self._generate_improvement_chart(report_data, report_id, chart_dir)
            if improvement_chart:
                chart_paths.append(improvement_chart)
            
            # 生成资源利用率图
            resource_chart = self._generate_resource_chart(report_data, report_id, chart_dir)
            if resource_chart:
                chart_paths.append(resource_chart)
            
            self.logger.info(f"性能图表已生成: {len(chart_paths)} 个文件")
            return chart_paths
        except Exception as e:
            self.logger.error(f"生成图表失败: {str(e)}")
            # 继续执行，不中断报告生成
            return chart_paths
    
    def _generate_improvement_chart(self, report_data: Dict[str, Any], report_id: str, chart_dir: str) -> Optional[str]:
        """
        生成性能提升对比图
        """
        try:
            plt.figure(figsize=(10, 6))
            
            # 获取数据
            target = report_data['optimization_analysis']['target_improvement']
            actual = report_data['optimization_analysis']['actual_improvement']
            
            # 创建柱状图
            bars = plt.bar(['目标提升', '实际提升'], [target, actual], color=['#ff9800', '#4caf50'])
            
            # 添加数值标签
            for bar in bars:
                height = bar.get_height()
                plt.text(bar.get_x() + bar.get_width()/2., height + 5,
                        f'{height:.1f}%', ha='center', va='bottom')
            
            # 设置图表属性
            plt.ylabel('性能提升百分比 (%)')
            plt.title('性能提升目标达成情况')
            plt.grid(axis='y', linestyle='--', alpha=0.7)
            
            # 保存图表
            chart_path = os.path.join(chart_dir, f"{report_id}_improvement.png")
            plt.tight_layout()
            plt.savefig(chart_path, dpi=300)
            plt.close()
            
            return chart_path
        except Exception as e:
            self.logger.warning(f"生成性能提升图表失败: {str(e)}")
            return None
    
    def _generate_resource_chart(self, report_data: Dict[str, Any], report_id: str, chart_dir: str) -> Optional[str]:
        """
        生成资源利用率图表
        """
        try:
            plt.figure(figsize=(12, 6))
            
            # 获取CPU和内存数据
            cpu_data = report_data['performance_metrics']['resource_utilization']['cpu']
            memory_data = report_data['performance_metrics']['resource_utilization']['memory']
            
            # 创建两个子图
            fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 6))
            
            # CPU使用率饼图
            cpu_labels = ['已使用', '未使用']
            cpu_values = [cpu_data['average'], 100 - cpu_data['average']]
            cpu_colors = ['#2196f3', '#e3f2fd']
            ax1.pie(cpu_values, labels=cpu_labels, autopct='%1.1f%%', colors=cpu_colors, startangle=90)
            ax1.set_title('平均CPU使用率')
            
            # 内存使用率饼图
            memory_labels = ['已使用', '未使用']
            memory_used_pct = memory_data['average_percentage']
            memory_values = [memory_used_pct, 100 - memory_used_pct]
            memory_colors = ['#4caf50', '#e8f5e9']
            ax2.pie(memory_values, labels=memory_labels, autopct='%1.1f%%', colors=memory_colors, startangle=90)
            ax2.set_title('平均内存使用率')
            
            # 保存图表
            chart_path = os.path.join(chart_dir, f"{report_id}_resources.png")
            plt.tight_layout()
            plt.savefig(chart_path, dpi=300)
            plt.close()
            
            return chart_path
        except Exception as e:
            self.logger.warning(f"生成资源利用率图表失败: {str(e)}")
            return None
    
    def compare_reports(self, report_paths: List[str], output_path: Optional[str] = None) -> str:
        """
        比较多个报告，生成对比分析
        
        Args:
            report_paths: 报告文件路径列表
            output_path: 输出路径
            
        Returns:
            对比报告路径
        """
        reports = []
        
        # 加载所有报告
        for path in report_paths:
            try:
                with open(path, 'r', encoding='utf-8') as f:
                    reports.append(json.load(f))
            except Exception as e:
                self.logger.error(f"加载报告 {path} 失败: {str(e)}")
        
        if not reports:
            raise ValueError("没有成功加载任何报告")
        
        # 生成对比数据
        comparison_data = self._generate_comparison_data(reports)
        
        # 生成对比报告
        if output_path is None:
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            output_path = os.path.join(self.report_dir, f"comparison_report_{timestamp}.html")
        
        self._generate_comparison_html(comparison_data, output_path)
        
        return output_path
    
    def _generate_comparison_data(self, reports: List[Dict[str, Any]]) -> Dict[str, Any]:
        """
        生成报告对比数据
        """
        # 提取各报告的关键指标
        comparison_points = []
        
        for i, report in enumerate(reports):
            point = {
                'id': i + 1,
                'timestamp': report['metadata']['generated_at'],
                'execution_time': report['test_summary']['execution_time'],
                'performance_improvement': report['optimization_analysis']['actual_improvement'],
                'cpu_utilization': report['performance_metrics']['resource_utilization']['cpu']['average'],
                'memory_utilization': report['performance_metrics']['resource_utilization']['memory']['average_percentage'],
                'parallel_degree': report['test_summary']['parallel_degree']
            }
            comparison_points.append(point)
        
        # 按时间排序
        comparison_points.sort(key=lambda x: x['timestamp'])
        
        return {
            'reports': comparison_points,
            'improvement_trend': self._calculate_trend(comparison_points)
        }
    
    def _calculate_trend(self, points: List[Dict[str, Any]]) -> Dict[str, Any]:
        """
        计算性能提升趋势
        """
        if len(points) < 2:
            return {'has_trend': False}
        
        # 计算性能提升变化
        first_improvement = points[0]['performance_improvement']
        last_improvement = points[-1]['performance_improvement']
        improvement_change = last_improvement - first_improvement
        
        # 计算时间减少变化
        first_time = points[0]['execution_time']
        last_time = points[-1]['execution_time']
        time_change = first_time - last_time
        
        return {
            'has_trend': True,
            'improvement_change': improvement_change,
            'time_change': time_change,
            'percentage_change': (improvement_change / first_improvement * 100) if first_improvement > 0 else 0
        }
    
    def _generate_comparison_html(self, comparison_data: Dict[str, Any], output_path: str):
        """
        生成对比HTML报告
        """
        # 这里可以实现更复杂的对比报告生成
        # 目前简化实现
        with open(output_path, 'w', encoding='utf-8') as f:
            f.write(f"""
            <!DOCTYPE html>
            <html lang="zh-CN">
            <head>
                <meta charset="UTF-8">
                <title>报告对比分析</title>
                <style>
                    body { font-family: Arial, sans-serif; margin: 20px; }
                    table { border-collapse: collapse; width: 100%; }
                    th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
                    th { background-color: #f2f2f2; }
                    tr:nth-child(even) { background-color: #f9f9f9; }
                </style>
            </head>
            <body>
                <h1>测试优化报告对比分析</h1>
                <table>
                    <tr>
                        <th>报告ID</th>
                        <th>生成时间</th>
                        <th>执行时间(秒)</th>
                        <th>性能提升(%)</th>
                        <th>CPU使用率(%)</th>
                        <th>内存使用率(%)</th>
                        <th>并行度</th>
                    </tr>
            """)
            
            for point in comparison_data['reports']:
                f.write(f"""
                    <tr>
                        <td>{point['id']}</td>
                        <td>{point['timestamp']}</td>
                        <td>{point['execution_time']:.2f}</td>
                        <td>{point['performance_improvement']:.1f}</td>
                        <td>{point['cpu_utilization']:.1f}</td>
                        <td>{point['memory_utilization']:.1f}</td>
                        <td>{point['parallel_degree']}</td>
                    </tr>
                """)
            
            f.write(f"""
                </table>
                
                {% if comparison_data['improvement_trend']['has_trend'] %}
                <h2>趋势分析</h2>
                <p>性能提升变化: {{ comparison_data['improvement_trend']['improvement_change']:.1f }}%</p>
                <p>时间减少: {{ comparison_data['improvement_trend']['time_change']:.2f }} 秒</p>
                {% endif %}
            </body>
            </html>
            """)

# 便捷函数
def generate_optimization_report(test_results: Dict[str, Any], 
                                performance_data: Dict[str, Any],
                                formats: List[str] = None,
                                output_dir: str = None) -> List[str]:
    """
    便捷函数：生成优化报告
    
    Args:
        test_results: 测试结果
        performance_data: 性能数据
        formats: 输出格式
        output_dir: 输出目录
        
    Returns:
        生成的报告文件路径列表
    """
    generator = ReportGenerator()
    return generator.generate_report(test_results, performance_data, formats, output_dir)

def compare_optimization_reports(report_paths: List[str], output_path: str = None) -> str:
    """
    便捷函数：比较多个优化报告
    
    Args:
        report_paths: 报告路径列表
        output_path: 输出路径
        
    Returns:
        对比报告路径
    """
    generator = ReportGenerator()
    return generator.compare_reports(report_paths, output_path)